package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;

/**
 * Author: Pepsi
 * Date: 2023/7/28
 * Desc:
 */
public class Flink06_reduce {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1",1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1",1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1",1607527996000L, 10));
        waterSensors.add(new WaterSensor("sensor_2",1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2",1607527995000L, 30));

        DataStreamSource<WaterSensor> waterSensorDataStreamSource = env.fromCollection(waterSensors);

        //方法引用，当返回结果是一个类的方法，可以直接用 类名::方法名 的形式进行调用
        waterSensorDataStreamSource.keyBy(WaterSensor::getId)
                // 要聚合的数据类型
                .reduce(new ReduceFunction<WaterSensor>() {
                    @Override
                    // value1 是历史聚合的数据  value2 是新进来的那条数据
                    public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                        return new WaterSensor(value1.getId(),value2.getTs()/10000,value1.getVc()+value2.getVc());
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
